package com.keur.money.ui.steps.fm

import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.provider.ContactsContract
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.keur.money.R
import com.keur.money.app.MyApp
import com.keur.money.base.utils.DensityUtils
import com.keur.money.base.utils.log.MullaLog
import com.keur.money.config.KeurConfigs
import com.keur.money.databinding.FmMullaStepPhonebookBinding
import com.keur.money.http.ApiService.addCommonParams
import com.keur.money.http.ApiService.addRandomParams
import com.keur.money.http.HttpHelper
import com.keur.money.mvp.ProFm
import com.keur.money.ui.steps.act.KeurStepsAct
import com.keur.money.ui.steps.adapter.KeurStepPhoneBookAdapter
import com.keur.money.utils.StringDeepCopy
import com.keur.money.utils.event.KeurBehaviorTracker
import com.keur.money.utils.event.KeurEventType
import com.keur.money.utils.helper.KeurCustomConfigsHelper
import com.keur.money.utils.helper.KeurUserPointsHelper
import org.json.JSONArray
import org.json.JSONObject
import java.util.regex.Pattern

/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/7/31 10:38
 * @Annotation：认证流程 - 联系人
 */
class KeurStepPhoneBookFm(): ProFm() {
    private var _binding: FmMullaStepPhonebookBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "Cannot access binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )

    private var personAdapter: KeurStepPhoneBookAdapter? = null
    private var cacheLastPersonItem = ""

    private var act: KeurStepsAct? = null
    private var stepItem: JSONObject? = null
    private var stepTitle = ""
    constructor(act: KeurStepsAct, stepItem: JSONObject): this(){
        this.act = act
        this.stepItem = stepItem
    }

    override fun getMullaRootView(inflater: LayoutInflater): View {
        _binding = FmMullaStepPhonebookBinding.inflate(inflater)
        return binding.root
    }

    override fun initMullaView() {
        rootViewBinding.containerLayout.setBackgroundColor(Color.parseColor("#00000000"))
        if (stepItem != null){
            _binding?.textStepTitle?.text = stepItem?.optString("showTitle")
        }
        val showKey1 = getString(R.string.step_phonebook_tips_repay_on_time)
        val showKey2 = getString(R.string.step_phonebook_tips_not_contact)
        val showText = String.format(getString(R.string.step_phonebook_tips),showKey1,showKey2)
        val startIndex1 = showText.indexOf(showKey1)
        val startIndex2 = showText.indexOf(showKey2)
        val tipsSpannable = SpannableString(showText)
        tipsSpannable.setSpan(ForegroundColorSpan(Color.parseColor("#FF26005D")), startIndex1, startIndex1 + showKey1.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        tipsSpannable.setSpan(ForegroundColorSpan(Color.parseColor("#FF26005D")), startIndex2, startIndex2 + showKey2.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        //加粗
//        contactTipsSpannable.setSpan(StyleSpan(Typeface.BOLD), startIndex1, startIndex1 + showKey1.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
//        contactTipsSpannable.setSpan(StyleSpan(Typeface.BOLD), startIndex2, startIndex2 + showKey2.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        _binding?.textStepTips?.text = tipsSpannable

        initMullaRecyclerViews()
        //积分
        _binding?.textPoints?.text = String.format(getString(R.string.step_phonebook_add_points),KeurCustomConfigsHelper.getMullaAddPersonPoints())
    }

    override fun initMullaListener() {
        //添加
        _binding?.addLayout?.setOnClickListener {
            if (cacheLastPersonItem.isNotEmpty()){
                personAdapter?.addLastItem(JSONObject(cacheLastPersonItem))
                personAdapter?.notifyDataSetChangedWrapper()
            }

            //最多添加50个联系人
            personAdapter?.let {
                if (it.itemCount >= 50){
                    _binding?.addLayout?.isEnabled = false
                    _binding?.addLayout?.setBackgroundResource(R.drawable.mulla_btn_disabled_12)
                } else {
                    _binding?.addLayout?.isEnabled = true
                    _binding?.addLayout?.setBackgroundResource(R.drawable.mulla_btn_pressed_12)
                }
            }
        }

        //提交
        _binding?.btnNext?.setOnClickListener {
            _binding?.root?.clearFocus()
            HttpHelper.addKeurEventAction(String.format(KeurEventType.CLICK.KEUR_CLICK_STEP_XX_NEXT, stepTitle),"")
            if (!isAllowSubmit() || stepItem == null){
                showMullaErrorTipsDialog(getString(R.string.tips_submit_error), stepTitle)
                return@setOnClickListener
            }
            val params = JSONObject().addCommonParams().addRandomParams().apply {
//                put("path",stepItem.optString("apiUrl").replace("/",""))
            }
            //拼接上传数据格式
            val paramArray = JSONArray()
            personAdapter?.let { adapter ->
                for (i in 0..< adapter.itemCount){
                    val obj = JSONObject()
                    val dataArray = adapter.getItem(i).optJSONArray("dataList")
                    dataArray?.let {
                        for (j in 0..<it.length()){
                            val item = it.optJSONObject(j)
                            val paramName = item.optString("paramName")
                            val selectItem = item.optJSONObject("selectItem")
                            var paramValue = selectItem?.optString("value")
                            if (paramName == "relation" && paramValue == getString(R.string.step_phonebook_relation_other)){
                                paramValue = selectItem?.optString("otherValue")
                                //如果关系为“Other”，输入的内容为纯数字，则直接传“Other”
                                if (isMullaCheckNumber(paramValue)){
                                    paramValue = getString(R.string.step_phonebook_relation_other)
                                }
                            }
                            obj.put(paramName,paramValue)
                        }
                    }
                    paramArray.put(obj)
                }
            }
            // TODO: Step Next 批量埋点上报
            KeurBehaviorTracker.getInstance(MyApp.app).reportImmediately(null)

            stepItem?.let {
                params.put(it.optString("contactParamName"),paramArray)
                val act = context as KeurStepsAct
                act.onMullaSubmitProcessAction(it.optString("apiUrl"),params)
            }
            //添加联系人增加的积分
            addMullaReceivePointsAction()
        }
    }

    override fun initMullaData() {
        //是否支持通讯录选择联系人
        val isPhoneBookPick = isMullaPhoneBookPick()
        val dataList = arrayListOf<JSONObject>()
        stepItem?.let { item ->
            stepTitle = item.optString("stepTitle")

            // TODO: 这里dataList需要深拷贝，否则列表会共用一个数据源
            val stringCopy = StringDeepCopy(item.optString("dataList"))
            for (i in 0..<item.optInt("itemCount")){
                val obj = JSONObject()
                val dataArray = JSONArray(stringCopy.content)
                for (j in 0..<dataArray.length()){
                    val dataObj = dataArray.optJSONObject(j)
                    dataObj.put("isPhoneBookPick",isPhoneBookPick)
                    dataObj.put("title",dataObj.optString("title"))
                    when(dataObj.optString("action")){
                        "CONTACT_GROUP_RELATION",
                        "SELECT",
                        -> {
//                            dataObj.put("action", "SELECT")
                            var relationShips = item.optJSONArray("relationShips")
                            if (KeurConfigs.isSwahili()){
                                relationShips = item.optJSONArray("relationShips_sw")
                            }
                            val valueArray = relationShips?.optJSONArray(i)
                            //手动添加一条Other
                            valueArray?.put(getString(R.string.step_phonebook_relation_other))
                            val values = JSONArray()
                            valueArray?.let {
                                for (n in 0..< it.length()) {
                                    val value = JSONObject()
                                    value.put("title", it.optString(n))
                                    if (KeurConfigs.isSwahili()){
                                        value.put("title_sw", it.optString(n))
                                    }
                                    value.put("value", it.optString(n))
                                    values.put(value)
                                }
                            }
                            dataObj.put("values", values)
                        }
                        "CONTACT_GROUP_PHONE" -> {//联系电话
                            dataObj.put("action","CONTACT_GROUP_PHONE")
                        }
                        "CONTACT_GROUP_NAME" -> {//联系人姓名
                            dataObj.put("action","CONTACT_GROUP_PHONE")
                        }
                        else -> {
                            dataObj.put("action","INPUT")
                        }
                    }
                }
                obj.put("stepTitle",stepTitle)
                obj.put("dataList",dataArray)
                dataList.add(obj)
            }
        }
        personAdapter?.data = dataList
        //缓存最后一个联系人item数据，用户新增item
        cacheLastPersonItem = StringDeepCopy(personAdapter?.lastItem.toString()).content

        //避免选择联系人之后重复打点
        HttpHelper.addKeurEventAction(KeurEventType.PAGE.KEUR_PAGE_STEP_PHONEBOOK_START)
    }

    /**
     * 初始化Views
     */
    private fun initMullaRecyclerViews(){
        //        _binding?.recyclerView?.setHasFixedSize(true)
        _binding?.recyclerView?.isNestedScrollingEnabled = false
        _binding?.recyclerView?.isFocusableInTouchMode = false //不需要焦点
        val layoutManager = LinearLayoutManager(context)
        layoutManager.orientation = RecyclerView.VERTICAL
        _binding?.recyclerView?.layoutManager = layoutManager
        val topDecoration = DensityUtils.dp2px(14f)
//        binding.recyclerView.addItemDecoration(LinearSpacingItemDecoration(0,0,0,topDecoration))
        personAdapter = KeurStepPhoneBookAdapter(binding.root,_binding?.recyclerView)
        _binding?.recyclerView?.adapter = personAdapter
        _binding?.recyclerView?.itemAnimator = DefaultItemAnimator()
        personAdapter?.setOnChildItemSelectMobileListener(object : KeurStepPhoneBookAdapter.IChildItemSelectMobileListener{
            override fun onChildSelectMobileClick(parentPosition: Int, childModel: JSONObject) {
                val startTime = System.currentTimeMillis()
                act?.pickPhonebook?.startPickPhoneBook { userName, userMobile ->
                    MullaLog.e(">>>>>>>>>>>>>>>>>>>>>$userName>>>>>>>$userMobile")
                    val subTimestamp = System.currentTimeMillis() - startTime
                    val parentItem = personAdapter?.getItem(parentPosition)
                    //设置联系人名称
                    val dataArray = parentItem?.optJSONArray("dataList")
                    if (dataArray != null) {
                        for (i in 0..<dataArray.length()) {
                            val itemObj = dataArray.optJSONObject(i)
                            if (itemObj.optString("paramName") == "fullName"){
                                val obj = JSONObject()
                                obj.put("title",userName)
                                obj.put("value",userName)
                                itemObj.put("selectItem",obj)
                                val subRemark = "${userName}$$${subTimestamp}"
                                HttpHelper.addKeurEventAction(String.format(KeurEventType.CLICK.KEUR_CLICK_STEP_XX_SELECT, "${parentItem.optString("stepTitle")}_${itemObj.optString("paramName")}_${parentPosition+1}"), subRemark)
                                continue
                            }
                            if (itemObj.optString("paramName") == "mobile"){
                                val obj = JSONObject()
                                obj.put("title",userMobile)
                                obj.put("value",userMobile)
                                itemObj.put("selectItem",obj)
                                val subRemark = "${userMobile}$$${subTimestamp}"
                                HttpHelper.addKeurEventAction(String.format(KeurEventType.CLICK.KEUR_CLICK_STEP_XX_SELECT, "${parentItem.optString("stepTitle")}_${itemObj.optString("paramName")}_${parentPosition+1}"), subRemark)
                                continue
                            }
                        }
                    }
                    personAdapter?.notifyItemChanged(parentPosition)

//                    val obj = JSONObject()
//                    obj.put("title",contactMobile)
//                    obj.put("value",contactMobile)
//                    childModel.put("selectItem", obj)
//                    contactAdapter?.notifyItemChanged(parentPosition)
//
//                    val parentItem = contactAdapter?.getItem(parentPosition)
//                    val subRemark = "${"$contactName:$contactMobile"}$$${System.currentTimeMillis() - startTime}"
//                    HttpHelper.addMullaEventAction(String.format(MullaEventType.CLICK.MULLA_CLICK_STEP_XX_SELECT, "${parentItem.optString("stepTitle")}_${childModel.optString("paramName")}_${parentPosition+1}"), subRemark)
                }
            }
        })
    }

    /**
     * 检查是否填写完整
     * 当且仅当 isMust=”NO“为非必填
     */
    private fun isAllowSubmit(): Boolean{
        val dataList = arrayListOf<JSONObject>()
        personAdapter?.let { adapter ->
            for (i in 0..<adapter.itemCount){
                val dataArray = adapter.getItem(i).optJSONArray("dataList")
                dataArray?.let {
                    for (j in 0..<it.length()){
                        val item = it.optJSONObject(j)
                        dataList.add(item)
                    }
                }
            }
        }
        //是否允许提交
        var isAllow = true
        for (i in 0..<dataList.size){
            val item = dataList[i]
            //存在 isMust && isMust == ”NO“  非必填
            if (item.has("isMust") && item.optString("isMust") == "NO"){
                continue
            }
            //必填 && 没有内容 || 内容为空
            if (!item.has("selectItem")){
                isAllow = false
                break
            }
            val selectItem = item.optJSONObject("selectItem")
            if (selectItem == null){
                isAllow = false
                break
            }
            val paramName = item.optString("paramName")
            val paramValue = selectItem.optString("value")
            if (paramValue.isEmpty()){
                isAllow = false
                break
            }
            if (paramName == "relation" && paramValue == getString(R.string.step_phonebook_relation_other) && selectItem.optString("otherValue","").isEmpty()){
                isAllow = false
                break
            }
        }
        return isAllow
    }

    /**
     * 增加联系人 添加积分
     */
    private fun addMullaReceivePointsAction(){
        stepItem?.let { item ->
            //默认添加联系人数量
            val defaultCount = item.optInt("itemCount")
            personAdapter?.let {
                //提交数量
                val submitCount = it.itemCount
                if (defaultCount == submitCount){
                    return
                }
                //获得的积分
                val receivePoints = (submitCount - defaultCount) * KeurCustomConfigsHelper.getMullaAddPersonPoints().toLong()
                KeurUserPointsHelper.saveMullsUserPointsAction("addContact",MyApp.app.getString(R.string.points_use_info_add_phonebook),receivePoints.toString())
            }
        }
    }

    /**
     * 是否支持通讯录选择
     */
    private fun isMullaPhoneBookPick(): Boolean{
        val intentPhonebook = Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI)
        val resolveInfoCType = requireContext().packageManager.resolveActivity(intentPhonebook, PackageManager.MATCH_DEFAULT_ONLY)
        return resolveInfoCType != null
    }

    /**
     * 是否全为数字
     */
    private fun isMullaCheckNumber(text: String?): Boolean {
        if (text.isNullOrEmpty()){
            return false
        }
        val formatLct = "^-?\\d+\\.?\\d*$"
        val patternLct = Pattern.compile(formatLct)
        return patternLct.matcher(text.trim()).matches()
    }

    override fun onStart() {
        super.onStart()
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpHelper.addKeurEventAction(KeurEventType.PAGE.KEUR_PAGE_STEP_PHONEBOOK_END)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}